const express = require('express');
const bodyParser = require('body-parser');
const morgan = require('morgan');

const ConnectWebSocket = require('./connectWebSocket');
const connectMongoDb = require('./connectMongoDB');
const usersRoute = require('./routes/users');
const chatsRoute = require('./routes/chats');

const app = express();
const PORT = 7000;

app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  if (req.method === 'OPTIONS') {
    res.send(200);
  } else {
    next();
  }
});

app.use(morgan(':method :url :status :res[content-length] - :response-time ms'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.use('/users', usersRoute);
app.use('/chats', chatsRoute);

// 建立 socket，path = /ws
const connectWs = new ConnectWebSocket({app, path: '/chats'})
connectWs.connect({PORT});

// 连接 mongodb
connectMongoDb();
